/**
 * Created by scutterry on 16/6/14.
 * v1.1 修复进度值为 NaN
 */
var ROOT = "resource/";
var Preload = (function(){
    function f(){
        this.imageUrl = [];
        this.jsonUrl = [];
        this.jsList = [];
        this.jsonLoaded = 0;
        this.imgLoaded = 0;
        this.jsLoaded = 0;
    }

    f.prototype.init = function(runFunc){
        this.runFunc = runFunc;
    };

    f.prototype.loadEgretResource = function(path){
        var self = this;
        self.preloadList = undefined;
        $.get(path, function(data){
            try{
                if(typeof data === "string"){
                    self.json = JSON.parse(data);
                }else{
                    self.json = data;
                }
            }catch(e){
                console.log("parse resource json error", e);
                return;
            }

            var arr = self.json.groups;
            var i = 0, len = arr? arr.length : 0;
            var obj;
            for(i = 0; i < len; i++){
                obj = arr[i];
                if(obj.name === "preload"){
                    var keys = obj.keys;
                    if(!keys){
                        console.log("kes error");
                        return;
                    }
                    keys = keys.replace(/\s/g, "");
                    self.preloadList = keys.split(",");
                }
            }

            //find the preload keys' url
            if(self.preloadList){
                len = self.preloadList.length;

                for(var i = 0; i < len; i++){
                    var p = self.preloadList[i];
                    var obj = self.findResourcePath(p);
                    if(obj){
                        if(obj.type === "image"){
                            self.imageUrl.push(obj.url);
                        }else if(obj.type === "json"){
                            self.jsonUrl.push(obj.url);
                        }else if(obj.type === "sheet"){
                            self.jsonUrl.push(obj.url);

                            var imgPath = obj.url.replace(/\.json$/, ".png");
                            self.imageUrl.push(imgPath);
                        }else if(obj.type === "font"){
                            self.jsonUrl.push(obj.url);
                            var fontPath = obj.url.replace(/\.fnt$/, ".png");
                            self.imageUrl.push(fontPath);
                        }else{
                            //todo sound
                        }
                    }
                }//for i
            }

//            console.log(self.imageUrl, self.jsonUrl);
            self.doLoadResource();
        });
    };

    f.prototype.findResourcePath = function(key){
        if(this.json){
            var arr = this.json.resources;
            len = arr? arr.length : 0;
            for(var i = 0; i < len; i++){
                var obj = arr[i];
                if(obj.name === key){
                    return obj;
                }
            }
        }
        return undefined;
    };

    f.prototype.doLoadResource = function(){
        this.i = 0;
        this.imgLoaded = 0;
        this.total = this.imageUrl.length + this.jsonUrl.length + this.jsList.length;
        this.loadInterval = setInterval(this.imageInterval.bind(this)
        , 40);
    };
    
    
    f.prototype.imageInterval = function(){
        if(this.i < len){
            var img = new Image;
            img.onload = this.loadPage.bind(this);
            img.src = ROOT + this.imageUrl[this.i];
            this.i++;
            if(this.i >= this.imageUrl.length){
                clearInterval(this.loadInterval);
                console.log("clear image interval-----")
            }
        }
    };

    f.prototype.loadPage = function(){
        console.log("image loaded")
        this.imgLoaded++;
        var percent = (100 - Math.floor(this.imgLoaded * 100 / this.total));
        this.updateView(percent);

        if(this.imgLoaded >= this.imageUrl.length){
            this.jsonLoaded = 0;
            if(this.jsonUrl && this.jsonUrl.length > 0){
                this.doLoadJson(ROOT + this.jsonUrl[0]);
            }
        }
    };

    f.prototype.doLoadJson = function(path){
        $.get(path, this.jsonComplete.bind(this));
    };

    f.prototype.jsonComplete = function(){
        this.jsonLoaded++;
        var percent = (100 - Math.floor((this.jsonLoaded + this.imgLoaded) * 100 / this.total));
        this.updateView(percent);
        if(this.jsonLoaded >= this.jsonUrl.length){
            //todo run egret

            if(this.jsList && this.jsList.length > 0){
                this.jsLoaded = 0;
                this.loadScript();
            }else{
                this.runGame();
            }


        }else{
            this.doLoadJson(ROOT + this.jsonUrl[this.jsonLoaded]);
        }
    };

    f.prototype.updateView = function(percent){
        percent = 1;
        percent = Math.max(percent, 1);
        var p = 100 - percent;
        $("#percentSpan").html(p + "%");
        $("#progressImg").css({left: (p - 100) + "%"});
    };




    f.prototype.loadScript = function(){
        if(isNaN(this.total)){
            this.total = this.imageUrl.length + this.jsonUrl.length + this.jsList.length;
        }
        var script = document.createElement("script");
        script.type = "text/javascript";
        var self = this;
        if (script.readyState){  //IE
            script.onreadystatechange = function(){
                if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                    script.onreadystatechange = null;
                    if(self.jsList.length > 0){
                        self.loadScript();
                    }else{
                        self.runGame();
                    }
                }
            };
        } else {  //Others
            script.onload = function(){
                self.jsLoaded++;
                var percent = (100 - Math.floor((self.jsonLoaded + self.imgLoaded + self.jsLoaded) * 100 / self.total));
                self.updateView(percent);
                if(self.jsList.length > 0){
                    self.loadScript();
                }else{
                    self.runGame();
                }
            };
        }

        if(this.jsList && this.jsList.length > 0){
            script.src = this.jsList.pop();
            document.getElementsByTagName("head")[0].appendChild(script);
        }else{
            this.runGame();
        }
    };

    f.prototype.runGame = function(){
        this.runFunc();

    };

    return f;
})();


var loadingCode = NaN;
function playLoading(){
    $("#loadingOuter").fadeIn();
    
}
function stopLoading() {
    if (!isNaN(loadingCode)) {
        clearInterval(loadingCode);
    }
    $("#loadingOuter").fadeOut();
};
function setProgress(percent) {
    console.log(percent);
    $("#percentSpan").html(percent + "%");
    $("#progressImg").css({left: (percent - 100) + "%"});
}

function showNews(res) {
    if (res && res.data && res.data.news_info) {
        console.log("news", res);
        $("#newsDiv").show();
        $("#title").html(res.data.news_info.title);
        // var str = res.data.news_info.content.replace();
        // str = str.replace("", ">");
        
        $("#content").html($("<div/>").html(res.data.news_info.content).text());
    }
}

function hideNews() {

}